import React, { useRef, useEffect, useState, useCallback } from 'react';  // 引入React核心库和常用Hook
import Webcam from 'react-webcam';  // 引入Webcam组件用于摄像头捕获
import styles from './Livestream.module.css';  // 引入CSS模块样式文件
import img1 from '../message/1.jpg';  // 引入图片资源
import img2 from '../message/2.jpg';  // 引入图片资源
import Peer from 'peerjs';  // 引入PeerJS库用于WebRTC通信
import { FaMicrophone, FaMicrophoneSlash, FaVideo, FaVideoSlash, FaSignal, FaUsers, FaRegSmile, FaMobile, FaDesktop, FaWifi, FaShareAlt, FaLink, FaCopy, FaCheck } from 'react-icons/fa';  // 引入图标组件
import { QRCodeSVG } from 'qrcode.react';  // 引入QRCode组件用于生成二维码

const url = 'http://192.168.108.119:5173/lview?id=broadcaster'
import { useNavigate } from 'react-router-dom';

const Livestream = () => {
  const navigate = useNavigate();
  // 状态管理
  const [viewerCount, setViewerCount] = useState(0);  // 观众数量状态
  const webcamRef = useRef(null);  // Webcam组件的ref引用
  const [peerId, setPeerId] = useState('');  // PeerJS生成的ID状态
  const peerRef = useRef(null);  // Peer实例的ref引用
  const [danmakuList, setDanmakuList] = useState([]);  // 弹幕列表状态
  const [giftAnimation, setGiftAnimation] = useState(null);  // 礼物动画状态
  const [isLive, setIsLive] = useState(false);  // 直播状态
  const [audioEnabled, setAudioEnabled] = useState(true);  // 麦克风状态
  const [videoEnabled, setVideoEnabled] = useState(true);  // 摄像头状态
  const [streamQuality, setStreamQuality] = useState('高清');  // 直播质量状态
  const [deviceType, setDeviceType] = useState('desktop');  // 设备类型状态
  const [networkStatus, setNetworkStatus] = useState('good');  // 网络状态
  const [localIpAddress, setLocalIpAddress] = useState('');  // 本地IP地址
  const [showShareLink, setShowShareLink] = useState(false);  // 是否显示分享链接
  const [linkCopied, setLinkCopied] = useState(false);  // 链接是否已复制
  const [availableDevices, setAvailableDevices] = useState({  // 可用设备状态
    videoinput: [],
    audioinput: []
  });
  const [selectedDevices, setSelectedDevices] = useState({  // 选中的设备
    videoinput: '',
    audioinput: ''
  });
  const [showDeviceSelector, setShowDeviceSelector] = useState(false);  // 是否显示设备选择器

  // 检测设备类型和获取本地IP地址
  useEffect(() => {
    // 检测是移动设备还是桌面设备
    const checkDeviceType = () => {
      const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
      setDeviceType(isMobile ? 'mobile' : 'desktop');
    };

    checkDeviceType();

    // 获取本地IP地址
    const getLocalIpAddress = async () => {
      try {
        // 使用WebRTC获取本地IP地址
        const pc = new RTCPeerConnection({
          iceServers: []
        });
        pc.createDataChannel('');
        await pc.createOffer().then(offer => pc.setLocalDescription(offer));

        // 等待ICE候选收集
        await new Promise(resolve => {
          pc.onicecandidate = (ice) => {
            if (ice.candidate) {
              const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
              const ipMatch = ipRegex.exec(ice.candidate.candidate);
              if (ipMatch && ipMatch[1] && !ipMatch[1].startsWith('127.')) {
                setLocalIpAddress(ipMatch[1]);
                resolve();
              }
            }
          };

          // 5秒超时
          setTimeout(resolve, 5000);
        });

        pc.close();
      } catch (error) {
        console.error('获取本地IP地址失败:', error);
        // 备用方法：使用服务器提供的IP地址
        try {
          const response = await fetch('/api/get-ip');
          const data = await response.json();
          if (data.ip) {
            setLocalIpAddress(data.ip);
          }
        } catch (err) {
          console.error('备用IP获取方法失败:', err);
          setLocalIpAddress('请连接到WiFi网络');
        }
      }
    };

    getLocalIpAddress();

    // 监听窗口大小变化，适配不同屏幕
    const handleResize = () => {
      checkDeviceType();
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // 获取可用的媒体设备
  useEffect(() => {
    const getAvailableDevices = async () => {
      try {
        // 请求权限
        await navigator.mediaDevices.getUserMedia({ video: true, audio: true });

        // 获取所有设备
        const devices = await navigator.mediaDevices.enumerateDevices();

        // 分类设备
        const videoDevices = devices.filter(device => device.kind === 'videoinput');
        const audioDevices = devices.filter(device => device.kind === 'audioinput');

        setAvailableDevices({
          videoinput: videoDevices,
          audioinput: audioDevices
        });

        // 默认选择第一个设备
        if (videoDevices.length > 0) {
          setSelectedDevices(prev => ({
            ...prev,
            videoinput: videoDevices[0].deviceId
          }));
        }

        if (audioDevices.length > 0) {
          setSelectedDevices(prev => ({
            ...prev,
            audioinput: audioDevices[0].deviceId
          }));
        }
      } catch (error) {
        console.error('获取设备失败:', error);
      }
    };

    getAvailableDevices();
  }, []);

  // 监测网络状态
  useEffect(() => {
    const checkNetworkStatus = () => {
      // 使用Navigator.connection API检测网络状态（如果可用）
      if ('connection' in navigator) {
        const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;

        if (connection) {
          const updateNetworkStatus = () => {
            const effectiveType = connection.effectiveType;
            const downlink = connection.downlink;

            if (effectiveType === '4g' && downlink > 5) {
              setNetworkStatus('excellent');
              setStreamQuality('超清');
            } else if (effectiveType === '4g' || (effectiveType === '3g' && downlink > 1)) {
              setNetworkStatus('good');
              setStreamQuality('高清');
            } else {
              setNetworkStatus('poor');
              setStreamQuality('标清');
            }
          };

          updateNetworkStatus();
          connection.addEventListener('change', updateNetworkStatus);
          return () => connection.removeEventListener('change', updateNetworkStatus);
        }
      }

      // 如果API不可用，使用简单的ping测试
      const pingTest = setInterval(() => {
        const start = Date.now();
        fetch('https://www.google.com', { mode: 'no-cors' })
          .then(() => {
            const duration = Date.now() - start;
            if (duration < 100) {
              setNetworkStatus('excellent');
            } else if (duration < 300) {
              setNetworkStatus('good');
            } else {
              setNetworkStatus('poor');
            }
          })
          .catch(() => setNetworkStatus('poor'));
      }, 30000); // 每30秒检测一次

      return () => clearInterval(pingTest);
    };

    const cleanup = checkNetworkStatus();
    return cleanup;
  }, []);

  // 主要副作用Hook，组件挂载时执行
  useEffect(() => {
    if (!isLive) return; // 只有在开播状态才初始化连接

    // 创建Peer实例，使用本地PeerJS服务器
    const peer = new Peer('broadcaster', {
      host: localIpAddress || 'localhost', // 使用获取到的本地IP地址
      port: 9000,
      path: '/myapp',
      secure: false,
      debug: 3, // 添加调试级别以便排查问题
      config: {
        iceServers: [
          { urls: 'stun:stun.l.google.com:19302' },// 使用STUN服务器
          { urls: 'stun:stun1.l.google.com:19302' },
          { urls: 'stun:stun2.l.google.com:19302' }
          // 移除TURN服务器，因为在局域网环境下通常不需要
        ]
      }
    });
    peerRef.current = peer;  // 保存peer实例到ref

    // Peer连接成功回调
    peer.on('open', (id) => {
      setPeerId(id);  // 设置peerId状态
      console.log('Broadcaster ID:', id);  // 打印peerId
    });

    // 监听连接错误
    peer.on('error', (err) => {
      console.error('PeerJS error:', err);
    });

    // 监听观众连接事件
    peer.on('connection', (conn) => {
      // 连接建立成功回调
      conn.on('open', () => {
        console.log('Viewer connected');
        setViewerCount(prev => prev + 1);

        // 发送主播设备信息给观众
        conn.send({
          type: 'broadcaster_info',
          deviceType: deviceType,
          networkStatus: networkStatus,
          streamQuality: streamQuality
        });

        // 处理ICE候选和SDP交换
        conn.peerConnection.onicecandidate = (event) => {
          if (event.candidate) {
            conn.send({
              type: 'ice_candidate',
              candidate: event.candidate
            });
          }
        };

        // 获取摄像头和麦克风媒体流，使用选定的设备
        navigator.mediaDevices.getUserMedia({
          video: selectedDevices.videoinput ? { deviceId: { exact: selectedDevices.videoinput } } : true,
          audio: selectedDevices.audioinput ? { deviceId: { exact: selectedDevices.audioinput } } : true
        })
          .then((stream) => {
            // 将媒体流设置为Webcam组件的视频源
            if (webcamRef.current && webcamRef.current.video) {
              webcamRef.current.video.srcObject = stream;
            }

            // 根据网络状态和设备类型调整视频质量
            const videoTracks = stream.getVideoTracks();
            if (videoTracks.length > 0) {
              const videoTrack = videoTracks[0];

              // 根据网络状态和设备类型设置视频约束
              let constraints = {};

              if (networkStatus === 'poor') {
                // 低质量设置
                constraints = {
                  width: { ideal: 640 },
                  height: { ideal: 360 },
                  frameRate: { max: 15 }
                };
              } else if (networkStatus === 'good') {
                // 中等质量设置
                constraints = {
                  width: { ideal: 1280 },
                  height: { ideal: 720 },
                  frameRate: { max: 30 }
                };
              } else {
                // 高质量设置
                constraints = {
                  width: { ideal: 1920 },
                  height: { ideal: 1080 },
                  frameRate: { max: 30 }
                };
              }

              // 应用约束
              videoTrack.applyConstraints(constraints)
                .catch(e => console.error('无法应用视频约束:', e));
            }

            // 向观众发起呼叫并发送媒体流
            const call = peer.call(conn.peer, stream);

            // 流传输成功回调
            call.on('stream', (remoteStream) => {
              console.log('Stream sent to viewer');
            });

            // 呼叫关闭回调
            call.on('close', () => {
              console.log('Call closed');
            });
          })
          .catch((error) => {
            console.error('无法获取摄像头:', error);  // 错误处理
            // 通知观众发生错误
            conn.send({
              type: 'error',
              message: '主播摄像头或麦克风访问失败'
            });
          });

        // 监听观众发送的数据
        conn.on('data', (data) => {
          if (data.type === 'danmaku') {  // 处理弹幕消息
            const newDanmaku = {
              id: Date.now(),  // 使用时间戳作为唯一ID
              text: data.text,  // 弹幕文本内容
              top: Math.random() * 70 + 10,  // 随机垂直位置(10%-80%)
            };
            setDanmakuList(prev => [...prev, newDanmaku]);  // 添加新弹幕
            // 8秒后移除该弹幕
            setTimeout(() => {
              setDanmakuList(prev => prev.filter(d => d.id !== newDanmaku.id));
            }, 8000);
          } else if (data.type === 'gift') {  // 处理礼物消息
            setGiftAnimation(data.gift);  // 显示礼物动画
            setTimeout(() => setGiftAnimation(null), 3000);  // 3秒后清除动画
          } else if (data.type === 'viewer_info') {
            // 接收观众设备信息
            console.log('观众设备信息:', data.deviceType);
            // 可以根据观众设备类型调整直播参数
          }
        });

        // 连接关闭回调
        conn.on('close', () => {
          console.log('Viewer disconnected');
          setViewerCount(prev => Math.max(0, prev - 1));  // 减少观众计数
        });
      });
    });

    // 组件卸载时的清理函数
    return () => {
      if (peerRef.current) {
        peerRef.current.destroy();  // 销毁Peer实例
      }
    };
  }, [isLive, deviceType, networkStatus, streamQuality, selectedDevices]); // 依赖isLive状态和其他相关状态，只在这些状态变化时执行

  // 开始/结束直播
  const toggleLivestream = () => {
    setIsLive(!isLive);
    if (!isLive) {
      // 开始直播时的逻辑
      console.log('开始直播');
    } else {
      // 结束直播时的逻辑
      setViewerCount(0);
      console.log('结束直播');
    }
  };

  // 切换麦克风状态
  const toggleAudio = () => {
    setAudioEnabled(!audioEnabled);
    if (webcamRef.current && webcamRef.current.video && webcamRef.current.video.srcObject) {
      webcamRef.current.video.srcObject.getAudioTracks().forEach(track => {
        track.enabled = !audioEnabled;
      });
    }
  };

  // 切换摄像头状态
  const toggleVideo = () => {
    setVideoEnabled(!videoEnabled);
    if (webcamRef.current && webcamRef.current.video && webcamRef.current.video.srcObject) {
      webcamRef.current.video.srcObject.getVideoTracks().forEach(track => {
        track.enabled = !videoEnabled;
      });
    }
  };

  // 切换直播质量
  const toggleStreamQuality = () => {
    const qualities = ['标清', '高清', '超清'];
    const currentIndex = qualities.indexOf(streamQuality);
    const nextIndex = (currentIndex + 1) % qualities.length;
    setStreamQuality(qualities[nextIndex]);

    // 通知所有连接的观众质量变化
    if (peerRef.current && peerRef.current.connections) {
      Object.values(peerRef.current.connections).forEach(connections => {
        connections.forEach(conn => {
          if (conn.open) {
            conn.send({
              type: 'quality_change',
              quality: qualities[nextIndex]
            });
          }
        });
      });
    }
  };

  // 切换设备
  const changeDevice = (kind, deviceId) => {
    setSelectedDevices(prev => ({
      ...prev,
      [kind]: deviceId
    }));

    // 如果正在直播，需要重新获取媒体流
    if (isLive && webcamRef.current && webcamRef.current.video) {
      navigator.mediaDevices.getUserMedia({
        video: kind === 'videoinput' ? { deviceId: { exact: deviceId } } : true,
        audio: kind === 'audioinput' ? { deviceId: { exact: deviceId } } : true
      })
        .then(stream => {
          webcamRef.current.video.srcObject = stream;

          // 更新所有观众的流
          if (peerRef.current && peerRef.current.connections) {
            Object.values(peerRef.current.connections).forEach(connections => {
              connections.forEach(conn => {
                if (conn.peerConnection) {
                  const senders = conn.peerConnection.getSenders();
                  senders.forEach(sender => {
                    if (sender.track.kind === (kind === 'videoinput' ? 'video' : 'audio')) {
                      const track = stream.getTracks().find(t => t.kind === sender.track.kind);
                      if (track) sender.replaceTrack(track);
                    }
                  });
                }
              });
            });
          }
        })
        .catch(error => console.error('切换设备失败:', error));
    }
  };



  // 渲染UI
  return (
    <>
      {/* 顶部信息栏 */}
      <div className={styles.appContainer}>
        {/* 主播信息和观众计数 */}
        <div className={styles.element1}>
          <div>
            <img src={img1} alt="图片1" />
          </div>
          <div>
            <span>Z</span>
            <p>{viewerCount} 人观看</p>
          </div>
        </div>

        {/* 预留元素区域 */}
        <div className={styles.element2}></div>

        {/* 其他信息展示 */}
        <div className={styles.element3}>
          <img src={img2} alt="图片2" />
          <span>1</span>
        </div>

        {/* 关闭按钮 */}
        <div className={styles.closeButton}>
          <span onClick={() => navigate('/')}>×</span>
        </div>
      </div>

      {/* 直播主容器 */}
      <div className={styles.broadcasterContainer}>
        <div className={styles.webcamContainer}>
          {/* 直播状态指示器 */}
          <div className={`${styles.liveIndicator} ${isLive ? styles.active : ''}`}>
            <span className={styles.liveIcon}></span>
            {isLive ? 'LIVE' : '未开播'}
          </div>

          {/* 局域网分享按钮 - 只在直播状态显示 */}
          {isLive && (
            <div className={styles.shareButton} onClick={() => setShowShareLink(!showShareLink)}>
              <FaShareAlt /> 分享直播
            </div>
          )}

          {/* 分享链接弹窗 */}
          {showShareLink && (
            <div className={styles.sharePopup}>
              <div className={styles.sharePopupHeader}>
                <h3>分享到局域网</h3>
                <span className={styles.closePopup} onClick={() => setShowShareLink(false)}>×</span>
              </div>
              <div className={styles.sharePopupContent}>
                <p>复制以下链接分享给同一局域网内的朋友：</p>
                <div className={styles.linkContainer}>
                  <FaLink />
                  <input
                    type="text"
                    readOnly
                    value={`http://${localIpAddress}:5173/lview?id=broadcaster`}
                    className={styles.shareLink}
                  />
                  <button className={styles.copyButton} onClick={() => {
                    navigator.clipboard.writeText(`http://${localIpAddress}:5173/lview?id=broadcaster`)
                      .then(() => {
                        setLinkCopied(true);
                        setTimeout(() => setLinkCopied(false), 2000);
                      })
                      .catch(err => console.error('复制失败:', err));
                  }}>
                    {linkCopied ? <FaCheck /> : <FaCopy />}
                  </button>
                </div>
                <div className={styles.qrContainer}>
                  <p>或扫描二维码：</p>
                  <div className={styles.qrPlaceholder}>
                    {localIpAddress && (
                      <QRCodeSVG
                        value={url}
                        size={150}
                        bgColor={"#ffffff"}
                        fgColor={"#000000"}
                        level={"L"}
                        includeMargin={true}
                      />
                    )}
                  </div>
                </div>
                <p className={styles.shareNote}>注意：确保接收方与您在同一个WiFi网络下</p>
              </div>
            </div>
          )}

          {/* 观众数量指示器 */}
          <div className={styles.viewerIndicator}>
            <FaUsers /> {viewerCount}
          </div>

          {/* 直播质量指示器 */}
          <div className={styles.qualityIndicator} onClick={toggleStreamQuality}>
            <FaSignal /> {streamQuality}
          </div>

          {/* 设备类型指示器 */}
          <div className={styles.deviceIndicator}>
            {deviceType === 'mobile' ? <FaMobile /> : <FaDesktop />} {deviceType === 'mobile' ? '移动设备' : '桌面设备'}
          </div>

          {/* 网络状态指示器 */}
          <div className={`${styles.networkIndicator} ${styles[networkStatus]}`}>
            <FaWifi /> {networkStatus === 'excellent' ? '极佳' : networkStatus === 'good' ? '良好' : '一般'}
          </div>

          {/* 设备选择器 */}
          <button
            className={`${styles.controlButton} ${styles.deviceButton}`}
            onClick={() => setShowDeviceSelector(!showDeviceSelector)}
          >
            切换设备
          </button>

          {showDeviceSelector && (
            <div className={styles.deviceSelector}>
              <div className={styles.deviceGroup}>
                <h3>摄像头</h3>
                {availableDevices.videoinput.map(device => (
                  <div
                    key={device.deviceId}
                    className={`${styles.deviceOption} ${selectedDevices.videoinput === device.deviceId ? styles.selected : ''}`}
                    onClick={() => changeDevice('videoinput', device.deviceId)}
                  >
                    {device.label || `摄像头 ${availableDevices.videoinput.indexOf(device) + 1}`}
                  </div>
                ))}
              </div>
              <div className={styles.deviceGroup}>
                <h3>麦克风</h3>
                {availableDevices.audioinput.map(device => (
                  <div
                    key={device.deviceId}
                    className={`${styles.deviceOption} ${selectedDevices.audioinput === device.deviceId ? styles.selected : ''}`}
                    onClick={() => changeDevice('audioinput', device.deviceId)}
                  >
                    {device.label || `麦克风 ${availableDevices.audioinput.indexOf(device) + 1}`}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Webcam组件显示摄像头画面 */}
          {videoEnabled ? (
            <Webcam ref={webcamRef} mirrored={true} />
          ) : (
            <div className={styles.videoDisabled}>
              <FaVideoSlash size={50} />
              <p>摄像头已关闭</p>
            </div>
          )}

          {/* 弹幕显示容器 */}
          <div className={styles.danmakuContainer}>
            {danmakuList.map((danmaku) => (
              <div
                key={danmaku.id}
                className={styles.danmaku}
                style={{ top: `${danmaku.top}%` }}
              >
                {danmaku.text}
              </div>
            ))}
          </div>

          {/* 礼物动画显示 */}
          {giftAnimation && (
            <div className={styles.giftAnimation}>
              <div className={styles.giftHeader}>收到礼物</div>
              <span>{giftAnimation.icon}</span>
              <div className={styles.giftName}>{giftAnimation.name || '礼物'}</div>
            </div>
          )}

          {/* 各种覆盖文本 */}
          <div className={styles.overlayText}>
            {isLive ? '直播中...' : '准备开播'}
          </div>
          <div className={styles.overlayText1}> 
          </div>
          <div className={styles.overlayText2}>
            <span>PK</span>
            <span>连线</span>
          </div>

          {/* 直播控制面板 */}
          <div className={`${styles.controlPanel} ${deviceType === 'mobile' ? styles.mobileControls : ''}`}>
            <button
              className={`${styles.controlButton} ${isLive ? styles.stopButton : styles.startButton}`}
              onClick={toggleLivestream}
            >
              {isLive ? '结束直播' : '开始直播'}
            </button>

            <button
              className={`${styles.controlButton} ${!audioEnabled ? styles.disabled : ''}`}
              onClick={toggleAudio}
            >
              {audioEnabled ? <FaMicrophone /> : <FaMicrophoneSlash />}
            </button>

            <button
              className={`${styles.controlButton} ${!videoEnabled ? styles.disabled : ''}`}
              onClick={toggleVideo}
            >
              {videoEnabled ? <FaVideo /> : <FaVideoSlash />}
            </button>

            <button className={styles.controlButton}>
              <FaRegSmile />
            </button>
          </div>
        </div>
        <h2 className={styles.broadcasterTitle}>
          {isLive ? '📡 直播中' : '🎬 主播端'}
        </h2>
      </div>
    </>
  );
};

export default Livestream;